/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.reply.rest;

import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.reply.domain.ReplyCount;
import me.zhengjie.modules.reply.repository.ReplyCountRepository;
import me.zhengjie.modules.reply.service.ReplyCountService;
import me.zhengjie.modules.reply.service.dto.ReplyCountQueryCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import me.zhengjie.utils.PageResult;
import me.zhengjie.modules.reply.service.dto.ReplyCountDto;

/**
* @website https://eladmin.vip
* @author wzy
* @date 2024-11-11
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "rep管理")
@RequestMapping("/api/replyCount")
public class ReplyCountController {

    private final ReplyCountService replyCountService;
    @Autowired
    private ReplyCountRepository ReplyCountRepository;

    @GetMapping("/pointsRules")
    @AnonymousAccess
    public ResponseEntity<List<Map<String, Object>>> getPointsRules() {
        // Example: Return predefined rules for demonstration purposes
        List<Map<String, Object>> rules = new ArrayList<>();
        ReplyCountRepository.findAll().stream().distinct().forEach(reply -> {
            Map<String, Object> rule = new HashMap<>();
            rule.put("count", reply.getCount());
            rule.put("points", 0); // Default points
            rules.add(rule);
        });
        return ResponseEntity.ok(rules);
    }
    @PostMapping("/pointsRules")
    @AnonymousAccess
    public ResponseEntity<Object> savePointsRules(@RequestBody List<Map<String, Object>> rules) {
        // Iterate through the rules and apply updates
        for (Map<String, Object> rule : rules) {
            Integer count = Integer.parseInt(rule.get("count").toString());
            Integer points = Integer.parseInt(rule.get("points").toString());

            // Find all entries with the same count and update their points
            List<ReplyCount> replies = ReplyCountRepository.findAllByCount(count);
            for (ReplyCount reply : replies) {
                reply.setGrade(points); // Ensure the ReplyCount entity has a `points` field
                ReplyCountRepository.save(reply);
            }
        }
        return ResponseEntity.ok("已更新");
    }
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('replyCount:list')")
    public void exportReplyCount(HttpServletResponse response, ReplyCountQueryCriteria criteria) throws IOException {
        replyCountService.download(replyCountService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询rep")
    @ApiOperation("查询rep")
    @PreAuthorize("@el.check('replyCount:list')")
    public ResponseEntity<PageResult<ReplyCountDto>> queryReplyCount(ReplyCountQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(replyCountService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增rep")
    @ApiOperation("新增rep")
    @PreAuthorize("@el.check('replyCount:add')")
    public ResponseEntity<Object> createReplyCount(@Validated @RequestBody ReplyCount resources){
        replyCountService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
    @PostMapping("/class/{activityid}")
    @AnonymousAccess
    public ResponseEntity<Object> add1ReplyCount(@PathVariable long activityid) {
        Integer id = Math.toIntExact(activityid);
        // 假设你有一个服务类处理数据
     //   boolean success = replyCountService.updateCount(resources.getId(), resources.getCount());
        ReplyCount m = ReplyCountRepository.findById(id).get();
        m.setCount(m.getCount()+1);
        ReplyCountRepository.save(m);
        return ResponseEntity.ok("更新成功");
    }
    @PutMapping
    @Log("修改rep")
    @ApiOperation("修改rep")
    @PreAuthorize("@el.check('replyCount:edit')")
    public ResponseEntity<Object> updateReplyCount(@Validated @RequestBody ReplyCount resources){
        replyCountService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除rep")
    @ApiOperation("删除rep")
    @PreAuthorize("@el.check('replyCount:del')")
    public ResponseEntity<Object> deleteReplyCount(@RequestBody Integer[] ids) {
        replyCountService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
